/*
 * Copyright 2017 cz<caoustc@163.com>
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.ovopark.firecar.manager;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.ovopark.firecar.bean.CrmDictBean;
import com.ovopark.firecar.bean.Privileges;
import com.ovopark.firecar.bean.User;
import com.ovopark.firecar.bean.WaterMarkBean;
import com.ovopark.firecar.common.Constants;
import com.ovopark.firecar.config.UserConfig;
import com.ovopark.firecar.utils.ListUtils;
import com.ovopark.firecar.utils.SharedPreferencesUtils;
import com.ovopark.firecar.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * if you want get app context, you need call attachContext method to init it.
 */
public class AppDataAttach {
    private static final String TAG = "AppDataAttach";
    private static Context mAppContext;
    private static User cacheUser;
    public static boolean mWapPlay = false;
    private static Application sApplication;

    private static List<Privileges> cachePrivileges;//用户菜单权限缓存

    private static List<CrmDictBean> crmDictBeans;//CRM字典项

    private static List<WaterMarkBean> waterMarkBeans;//水印配置

    public static Application getApplication() {
        return sApplication;
    }

    public static void attachContext(Application application) {
        sApplication = application;
        mAppContext = application.getApplicationContext();
    }

    public static Context getApplicationContext() {
        if (mAppContext == null) {
            Log.e("AppDataAttach", "app context not init !!!");
            throw new RuntimeException("if you need context, you must call attachContext first");
        }
        return mAppContext;
    }

    public static void attachUser(User user) {
        Log.i(TAG, "attachUser(User user) start~");
        cacheUser = user;
        saveCacheUser(user);
    }

    public static User getUser() {
        if (cacheUser == null) {
            Log.i(TAG, "getCacheUser()");
            cacheUser = getCacheUser();
        }
        return cacheUser;
    }

    /**
     * 获取USER中的信息
     *
     * @param userDef 枚举
     * @return
     */
    public static String getUserDef(@UserConfig.UserDef int userDef) {
        if (cacheUser == null) {
            cacheUser = getCacheUser();
        }
        return UserConfig.getUserByDef(cacheUser, userDef);
    }

    public static User getUser(Context context) {
        if (mAppContext == null && context != null) {
            mAppContext = context.getApplicationContext();
        }
        if (cacheUser == null) {
            cacheUser = getCacheUser();
        }
        return cacheUser;
    }

    private static void saveCacheUser(User user) {
        Log.i(TAG, "saveCacheUser(User user) start~");
        try {
            if (user != null && mAppContext != null) {
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .removeParam(mAppContext, Constants.Prefs.CACHE_USER);
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .setParam(mAppContext, Constants.Prefs.CACHE_USER, JSONObject.toJSONString(user));
                Log.i(TAG, "saveCacheUser:token>>>>>" + user.getToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static User getCacheUser() {
        Log.i(TAG, "getCacheUser()");
        try {
            String userJson = (String) SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                    .getParam(mAppContext, Constants.Prefs.CACHE_USER, "");
            Log.i(TAG, "getCacheUser():" + userJson);
            if (!StringUtils.isBlank(userJson)) {
                User user = JSONObject.parseObject(userJson, User.class);
                Log.i(TAG, "get shared prefrerence user token: " + (user != null ? user.getToken() : null));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "解析错误：" + e.getMessage());
        }
        return new User();
    }

    public static void clearCacheUser() {
        cacheUser = null;
        if (mAppContext != null) {
            SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                    .removeParam(mAppContext, Constants.Prefs.CACHE_USER);
        }
    }


    /**
     * 获取权限 --无参构造
     *
     * @return
     */
    public static List<Privileges> getPrivileges() {
        if (cachePrivileges == null) {
            cachePrivileges = getCachePrivileges();
        }
        return cachePrivileges;
    }

    /**
     * 获取权限
     *
     * @param context
     * @return
     */
    public static List<Privileges> getPrivileges(Context context) {
        if (mAppContext == null && context != null) {
            mAppContext = context.getApplicationContext();
        }
        if (cachePrivileges == null) {
            cachePrivileges = getCachePrivileges();
        }
        return cachePrivileges;
    }

    /**
     * 缓存权限列表
     *
     * @param privileges
     */
    public static void saveCachePrivileges(List<Privileges> privileges) {
        try {
            if (!ListUtils.isEmpty(privileges) && mAppContext != null) {
                cachePrivileges = privileges;
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .removeParam(mAppContext, Constants.Prefs.CACHE_PRIVILEGES);
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .setParam(mAppContext, Constants.Prefs.CACHE_PRIVILEGES, JSONObject.toJSONString(privileges));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取缓存的权限
     *
     * @return
     */
    public static List<Privileges> getCachePrivileges() {
        try {
            if (mAppContext != null) {
                String privilegesJson = (String) SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .getParam(mAppContext, Constants.Prefs.CACHE_PRIVILEGES, null);
                if (!StringUtils.isBlank(privilegesJson)) {

                    return JSONObject.parseArray(privilegesJson, Privileges.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<Privileges>();
    }



    /**
     * 获取字典项 --无参构造
     *
     * @return
     */
    public static List<CrmDictBean> getDicts() {
        if (crmDictBeans == null) {
            crmDictBeans = getCacheDicts();
        }
        return crmDictBeans;
    }
    /**
     * 缓存CRM字典项
     *
     * @param crmDictBeanList
     */
    public static void saveCacheDicts(List<CrmDictBean> crmDictBeanList) {
        try {
            if (!ListUtils.isEmpty(crmDictBeanList) && mAppContext != null) {
                crmDictBeans = crmDictBeanList;
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .removeParam(mAppContext, Constants.Prefs.CACHE_DICTS);
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .setParam(mAppContext, Constants.Prefs.CACHE_DICTS, JSONObject.toJSONString(crmDictBeanList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取CRM字典项
     *
     * @return
     */
    public static List<CrmDictBean> getCacheDicts() {
        try {
            if (mAppContext != null) {
                String dictJson = (String) SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .getParam(mAppContext, Constants.Prefs.CACHE_DICTS, "");
                if (!StringUtils.isBlank(dictJson)) {

                    return JSONObject.parseArray(dictJson, CrmDictBean.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<CrmDictBean>();
    }

    /**
     * 缓存水印
     *
     * @param waterMarkBeanList
     */
    public static void saveCacheWatermark(List<WaterMarkBean> waterMarkBeanList) {
        try {
            if (!ListUtils.isEmpty(waterMarkBeanList) && mAppContext != null) {
                //waterMarkBeans = waterMarkBeanList;
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .removeParam(mAppContext, Constants.Prefs.CACHE_WATERMARK);
                SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .setParam(mAppContext, Constants.Prefs.CACHE_WATERMARK, JSONObject.toJSONString(waterMarkBeanList));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取水印
     *
     * @return
     */
    public static List<WaterMarkBean> getCacheWatermark() {
        try {
            if (mAppContext != null) {
                String dictJson = (String) SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                        .getParam(mAppContext, Constants.Prefs.CACHE_WATERMARK, "");
                if (!StringUtils.isBlank(dictJson)) {

                    return JSONObject.parseArray(dictJson, WaterMarkBean.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<WaterMarkBean>();
    }
    /**
     * 清空权限缓存
     */
    public static void clearCachePrivileges() {
        cachePrivileges = null;
        if (mAppContext != null) {
            SharedPreferencesUtils.getInstance(Constants.Prefs.PREFRENCE_NAME)
                    .removeParam(mAppContext, Constants.Prefs.CACHE_PRIVILEGES);
        }
    }
}
